package com.wzw.shoppingcart.controller;

import com.wzw.shoppingcart.entity.Product;
import com.wzw.shoppingcart.entity.Promotion;
import com.wzw.shoppingcart.service.PromotionService;
import com.wzw.shoppingcart.service.ProductService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.stream.Collectors;

import static com.wzw.shoppingcart.constant.Constant.PRODUCT_DISCOUNT;

/**
 *@author wzw
 * 2023/4/14
 */
@RestController
@RequestMapping("/promotion")
@RequiredArgsConstructor
@Slf4j
public class PromotionController {

    private final PromotionService promotionService;
    private final ProductService productService;

    @PostMapping
    public boolean productPromotion(@RequestBody Promotion promotion){
       return promotionService.save(promotion);
    }

    @PostMapping("/specify")
    public boolean specifyDiscount(@RequestBody List<Integer> productIds){

        List<Product> productList = productIds.stream()
                .filter(id -> !promotionService.exist(id, PRODUCT_DISCOUNT))
                .map(productService::getProductById).collect(Collectors.toList());

        List<Promotion> promotions = productList.stream().map(p -> {
            Promotion promotion = new Promotion();
            promotion.setProductId(p.getProductId());
            promotion.setDiscountType(PRODUCT_DISCOUNT);
            return promotion;
        }).collect(Collectors.toList());
      return   promotionService.saveBatch(promotions);
    }


}
